package com.xiaoqi.Security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoqi.pojo.Permission;
import com.xiaoqi.pojo.Role;
import com.xiaoqi.pojo.User;
import com.xiaoqi.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author PC
 * creationTime: 2022/11/23 14:11
 */
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过名字查询角色以及权限
        User userInDb = userService.findByName(username);
        //判断是否为空
        if (null!=userInDb){
            //获取用户密码
            String password = userInDb.getPassword();
            //创建一个用来装权限与角色的容器
            List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
            //所有的角色与权限的需要被他包装如何放入grantedAuthorityList
            GrantedAuthority sga = null;
            //获取当前用户的所有角色
            Set<Role> roles = userInDb.getRoles();
            //判断是否有角色
            if (null!=roles){
                //遍历角色将他们让SimpleGrantedAuthority包装
                for (Role role : roles) {
                    //包装
                    sga = new SimpleGrantedAuthority(role.getKeyword());
                    //加入
                    grantedAuthorityList.add(sga);
                    //获取所有的权限
                    Set<Permission> permissions = role.getPermissions();
                    //判断是否有权限
                    if (null!=permissions){
                        //遍历权限将他们让SimpleGrantedAuthority包装
                        for (Permission permission : permissions) {
                            sga = new SimpleGrantedAuthority(permission.getKeyword());
                            grantedAuthorityList.add(sga);
                        }
                    }
                }
            }

            org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(username,password,grantedAuthorityList);
            return user;
        }


        return null;
    }
}
